<?php

require_once 'google/appengine/api/mail/Message.php';

use Carbon\Carbon as Carbon;
use google\appengine\api\mail\Message;

class FeedbackController extends BaseController {

  public function showIndex() {
    return View::make('pages.feedback');
  }

  public function sendFeedback() {
    $date = new Carbon('now');
    $date->subMinutes(5);
    $old  = Auth::user()->emails()->where('sent', '=', 1)->where('created_at', '>', $date->format('Y-m-d H:i:s'))->count();
    if ($old > 0) {
      Session::flash('error', 'You sent feedback less than 5 minutes ago. Please wait.');
      return Redirect::to('/feedback')->withInput();
    }
    $same = Auth::user()->emails()->where('sent', '=', 1)->where('feedback', '=', Input::get('feedback'))->count();
    if ($same > 0) {
      Session::flash('error', 'Unknown error.');
      return Redirect::to('/feedback')->withInput();
    }
    if (is_null(Input::get('feedback')) || strlen(Input::get('feedback')) == 0) {
      Session::flash('error', 'Do fill something in.');
      return Redirect::to('/feedback')->withInput();
    }
    // process
    $email                 = new Email;
    $email->tempestuser_id = Auth::user()->id;
    $email->feedback       = Input::get('feedback');
    $email->save();

    // send it.
    $view         = View::make('emails.feedback')->with('email', Auth::user()->email)->with('id', Auth::user()->id)->with('feedback', Input::get('feedback'));
    $message_body = $view->render();

    $mail_options = array(
        'sender'   => Config::get('tempest.from'),
        'to'       => Auth::user()->email,
        'bcc'      => Config::get('tempest.bcc'),
        'subject'  => "Feedback from nder-tempest.appspot.com",
        'textBody' => $message_body
    );

    try {
      $message = new Message($mail_options);
      $message->send();
    } catch (\InvalidArgumentException $e) {
      var_dump($message_body);
      var_dump($e);
      exit;
      App::abort(500);
    }
    $email->sent = 1;
    $email->save();



    Session::flash('success', 'Your feedback has been sent. Thanks!');
    return Redirect::to('/');
  }

}